﻿#include "ssSystemMgr.h"
#include "../node/ssRootNode.h"
#include "../element/camera/ssCamera.h"


namespace StarSeeker
{

ssSystemMgr::ssSystemMgr(ssRootNode* root)
	:m_root(root)
{
}

ssSystemMgr::~ssSystemMgr()
{
}

void ssSystemMgr::Update()
{
	m_transformSystem.Empty();
	m_cameraSystem.Empty();
	m_lightSystem.Empty();
	m_renderSystem.Empty();

	ssList<ssNode*>& list = m_root->GetChildren();
	ssList<ssNode*>::Iterator itr = list.Begin();
	while (itr.IsVaild())
	{
		CheckNode(*itr);
		++itr;
	}

	m_transformSystem.Work();
	m_lightSystem.Work();
	m_cameraSystem.Work();

	//离屏渲染
	bool r2t = false;
	ssCamera* pCamera = 0;
	for (u32 i = 0; i < m_cameraSystem.m_nodes.Count(); ++i)
	{
		pCamera = SS_DYNAMIC_CAST(ssCamera*, m_cameraSystem.m_nodes[i]->GetComponent(ssComponent::SS_COMPONENT_CAMERA));
		if (pCamera->R2TBegin())
		{
			r2t = true;
			pCamera->ActiveCamera();
			pCamera->ClearBuffer();
			m_renderSystem.Work();
		}
	}
	if (r2t)
	{
		ssCamera::s_currentCamera->R2TEnd();
	}
	//主相机渲染
	if (ssCamera::s_mainCamera && ssCamera::s_mainCamera->m_enable)
	{
		ssCamera::s_mainCamera->ActiveCamera();
		ssCamera::s_mainCamera->ClearBuffer();
		m_renderSystem.Work();
	}
}

void ssSystemMgr::CheckNode(ssNode* node)
{
	if (node && node->m_enable)
	{
		ssTransform* pTransform = SS_DYNAMIC_CAST(ssTransform*, node->GetComponent(ssComponent::SS_COMPONENT_TRANSFORM));
		if (pTransform && pTransform->hasDirty())
		{
			m_transformSystem.m_nodes.PushBack(node);
		}
		ssComponent* pCamera = node->GetComponent(ssComponent::SS_COMPONENT_CAMERA);
		if (pCamera && pCamera->m_enable)
		{
			m_cameraSystem.m_nodes.PushBack(node);
		}
		ssComponent* pLight = node->GetComponent(ssComponent::SS_COMPONENT_LIGHT);
		if (pLight && pLight->m_enable)
		{
			m_lightSystem.m_nodes.PushBack(node);
		}
		m_renderSystem.CheckNode(node);

		ssList<ssNode*>& list = node->GetChildren();
		ssList<ssNode*>::Iterator itr = list.Begin();
		while (itr.IsVaild())
		{
			CheckNode(*itr);
			++itr;
		}
	}
}

}
